package com.zxm.web.controller.message;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.zxm.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Objects;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @Author silence.Z
 * @Date 2022/8/29 13:15
 * @PackageName:com.zxm.web.controller.message
 * @ClassName: SseConnection
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/sse")
public class SseController {

	private static Cache<String, LinkedBlockingDeque<SseEvent>> sseCache = CacheBuilder.newBuilder()
			.maximumSize(1000)
			.expireAfterWrite(60, TimeUnit.MINUTES)
			.build();

	/**
	 * sse 连接服务
	 */
	@GetMapping("/sseEvent/{userId}")
	public SseEmitter push(@PathVariable("userId") String userId) {
		return SseEmitterServer.connect(userId);
	}

	//IE 浏览器不支持SSE 采用轮循
	@GetMapping("/sseEventIE/{userId}")
	public ResponseEntity pushIe(@PathVariable("userId") String userId) {
		if (StringUtils.isEmpty(userId)) {
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(" userId is Empty ! ");
		}
		log.info("IE 连接，userId = {} ", userId);
		try {
			SseEvent poll = Objects.requireNonNull(sseCache.getIfPresent(userId)).poll();
			return poll == null ? ResponseEntity.status(HttpStatus.BAD_REQUEST).body("连接失败！") : ResponseEntity.ok().body(poll.getMsg());
		} catch (Exception e) {
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
		}
	}

	static boolean publicMsg(SseEvent event) {
		LinkedBlockingDeque<SseEvent> ifPresent = sseCache.getIfPresent(event.getUserId());
		if (ifPresent == null) {
			sseCache.put(event.getUserId(), new LinkedBlockingDeque<SseEvent>());
		}
		log.info("添加到队列，userId：{} ", event.getUserId());
		return Objects.requireNonNull(sseCache.getIfPresent(event.getUserId())).offer(event);
	}
}
